package com.common.core.utils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import com.common.core.R;
import com.common.http.basecore.utils.LogInfo;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;




public class CommonCoreUtil {

    private static final String TAG = CommonCoreUtil.class.getSimpleName();
    public static long lastClickTime = 0;

    public static long currentClickTime = 0;
    public static boolean checkClickEvent() {
        return checkClickEvent(500);
    }

    public static boolean checkScrollEvent() {
        return checkClickEvent(1000);
    }

    public static boolean checkClickEvent(long interval) {
        currentClickTime = System.currentTimeMillis();
        if (currentClickTime - lastClickTime > interval) {
            lastClickTime = currentClickTime;
            LogInfo.log(TAG,"lastClickTime: "+lastClickTime);
            return true;
        } else {
            lastClickTime = currentClickTime;
            LogInfo.log(TAG, "lastClickTime: " + lastClickTime);
            return false;
        }
    }
//    private final static Map<String, String> relation = getDataRelationMap(YanxiuApplication.getInstance(), R.array.intelli_exe_arrays);
    /**
     * appdeviceid:deviceid+macaddress
     *
     * @param context
     * @return
     */
    @Deprecated
    public static String getAppDeviceId(Context context) {

        TelephonyManager telephonyManager = (TelephonyManager) ContextProvider.getApplicationContext().getSystemService(
                Context.TELEPHONY_SERVICE);
        String deviceId = telephonyManager.getDeviceId();

        WifiManager wifiManager = (WifiManager)ContextProvider.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        if (wifiInfo != null) {
            String macAddress = wifiInfo.getMacAddress();
            deviceId = deviceId + macAddress;
        }

        if (deviceId == null || "".equals(deviceId.trim())) {
            deviceId = "-";
        }

        return MD5Tool.getStringMD5(deviceId);
    }



    //获取rom厂商
    public static String getRomFacturer() {

        return "" + Build.MANUFACTURER;
    }


    /**
     * 获取客户端版本号
     *
     * @param context
     * @return
     */
    public static int getClientVersionCode(Context context) {
        if (context == null) {
            return 0;
        }
        try {
            PackageInfo packInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
    public static int getSDK() {
        return Build.VERSION.SDK_INT;
    }
    /**
     * 得到客户端版本名
     */
    public static String getClientVersionName(Context context) {
        try {
            PackageInfo packInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取osversionname
     */
    public static String getOSVersionName() {
        return Build.VERSION.RELEASE;
    }

    public static String getOSVersionCode() {
        int version = -1;
        try {
            version = Integer.valueOf(Build.VERSION.SDK_INT);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return String.valueOf(version);
    }


    /**
     * 获取厂商品牌
     */
    public static String getBrandName() {
        String brand = Build.BRAND;
        if (brand == null || brand.length() <= 0) {
            return "";
        } else {
            return getData(brand);
        }
    }

    /**
     * 获取modelname
     *
     * @return
     */
    public static String getModelName() {
        String model = Build.MODEL;
        if (model == null || model.length() <= 0) {
            return "";
        } else {
            return getData(model);
        }
    }

    private static String getData(String data) {
        if (data == null || data.length() <= 0) {
            return "-";
        } else {
            return data.replace(" ", "_");
        }
    }


    /**
     * 获取cpu核数
     */
    public static int getNumCores() {
        // Private Class to display only CPU devices in the directory listing
        class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                // Check if filename is "cpu", followed by a single digit number
                return Pattern.matches("cpu[0-9]", pathname.getName());
            }
        }

        try {
            // Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            // Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            // Return the number of cores (virtual CPU devices)
            return files.length;
        } catch (Exception e) {
            // Default to return 1 core
            return 1;
        }
    }



    /**
     * 验证邮箱格式是否正确
     *
     * @param email
     * @return
     */
    public static boolean emailFormats(String email) {
        if (email == null)
            return false;
        String regular = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    /**
     * 校验验证码是数字或者字母
     */
    public static boolean verFormat(String ver) {
        if (ver == null)
            return false;
        String regular = "^[a-zA-Z0-9_]{4}$";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(ver);
        return matcher.matches();
    }

    /**
     * 验证密码是否是 数字和字母，英文符号 长度6-16,区分大小写
     */
    public static boolean passwordFormat(String password) {
        if (password == null)
            return false;

        String regular = "^[a-zA-Z0-9!`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]{6,16}$";
        //String regular = "^[,\\.;\\:\"\'!a-zA-Z0-9_]{6,16}$";
        //String regular = "/^[\w.]{6,16}$/";
        Pattern pattern = Pattern.compile(regular);
        Matcher matcher = pattern.matcher(password);
        return matcher.matches();
    }

    /**
     * 验证注册手机号码是否正确
     */
    public static boolean isMobileNO(String mobiles) {
        if (mobiles == null) {
            return false;
        }
        Pattern p = Pattern.compile("^(1)\\d{10}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断sdcard是否存在
     *
     * @return
     */
    public static boolean sdCardMounted() {
        final String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED) && !state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
    }




	   /**  
	      得到等分的值
     *
     * @param resParams
     * @param divideParams
     * @return
     */
    public static int getDividePx(int resParams,int divideParams){
        if(divideParams==0){
            throw new IllegalArgumentException("divideParams cannot be zero");
        }
        return resParams/divideParams;
    }


    /**
     * 获取imei号
     *
     * @return
     */
    public static String getIMEI() {
        try {
            String deviceId = ((TelephonyManager)ContextProvider.getApplicationContext().getSystemService(
                    Context.TELEPHONY_SERVICE)).getDeviceId();
            if (null == deviceId || deviceId.length() <= 0) {
                return "";
            } else {
                return deviceId.replace(" ", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 根据资源ID得到View
     */
    public static View inflate(Context context, int resource, ViewGroup root, boolean attachToRoot) {
        return LayoutInflater.from(context).inflate(resource, root, attachToRoot);
    }



    /**
     * 验证是否是手机号的格式
     */
    public static boolean isMobileNo(String mobiles) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("^((1[0-9][0-9]))\\d{8}$");
            Matcher m = p.matcher(mobiles);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 验证是否是身份证号格式
     */
    public static boolean isCard(String str) {
        String reg15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
        String reg18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$";
        boolean flag = false;
        try {
            Pattern p;
            if (str.length() == 15) {
                p = Pattern.compile(reg15);
            } else {
                p = Pattern.compile(reg18);
            }
            Matcher m = p.matcher(str);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 是否是邮箱格式
     */
    public static boolean isEmail(String str) {
        boolean flag = false;
        try {
            Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
            Matcher m = p.matcher(str);
            flag = m.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }



    /**
     * 设置用户代理 UA
     * @param context
     * 例如： mWebView.getSettings().setUserAgentString（）；传入方法参数
     * @return
     */
    public static String createUA(Context context){
        String ua = "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) " + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1";
        ua += " " + "YanxiuMobileClient_" + getClientVersionCode(context) + "_android";
        return ua;
    }

    public static void hideSoftInput(View view){
        if(view==null){
            return;
        }
        InputMethodManager imm = ( InputMethodManager ) view.getContext( ).getSystemService(
                Context.INPUT_METHOD_SERVICE );
        if ( imm.isActive() ) {
            imm.hideSoftInputFromWindow( view.getApplicationWindowToken( ) , 0 );
        }
    }



    public static <T extends Comparable<T>> boolean compare(List<T> a, List<T> b) {
        if(a.size() != b.size())
            return false;
        return a.containsAll(b) && b.containsAll(a);
    }

    /**
     * 拷贝对象
     * @param <T>
     * @param <T>
     * @return
     */
    public static <T,P>T copyBean(P p, Class<T> clazz){
        if(p == null)
            return null;
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (Exception e1) {
            // do nothind
            e1.printStackTrace();
        }
        Field[] fields = null;
        try{
            fields = p.getClass().getDeclaredFields();
        }catch(Exception e){
            e.printStackTrace();
        }
        for(int i = 0; i < fields.length; i++){
            try {
                fields[i].setAccessible(true);
                String fieldName = fields[i].getName();
                Object fieldValue = fields[i].get(p);
                try{
                    Field filed = clazz.getDeclaredField(fieldName);
                    filed.setAccessible(true);
                    filed.set(t, fieldValue);
                }catch(Exception e){
                    // do nothing
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return t;
    }

    public static boolean checkBrowser(Context context, String packageName) {

        boolean isInstalled = false;
        try {
            PackageManager pm = context.getPackageManager();
            pm.getApplicationInfo(packageName, PackageManager.GET_ACTIVITIES);
            isInstalled = true;
        } catch (NameNotFoundException e) {
            isInstalled = false;
        }
        return isInstalled;
    }

    public static void measureView(View childView) {
        ViewGroup.LayoutParams p = childView.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
        int height = p.height;
        int childHeightSpec;
        if (height > 0) {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(height,
                    View.MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
        }
        childView.measure(childWidthSpec, childHeightSpec);
    }




    /**
     * Calling
     */
     public static void callPhone(Context context,String phoneNum){
         if(context==null){
             return;
         }
         if(StringUtils.isEmpty(phoneNum)){
             return;
         }

         Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + phoneNum));
         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
         context. startActivity(intent);


     }

    /**
     * 对View设置不同状态时其文字颜色。
     */
    public static ColorStateList createColorStateList (int normal, int pressed) {
        //colors里面存放的事颜色值而不是颜色id,如果是自定义颜色需要使用getResources().getColor(R.color.white)
        int[] colors = new int[]{pressed, pressed, normal, pressed, normal};
        int[][] states = new int[5][];
        states[0] = new int[]{android.R.attr.state_pressed, android.R.attr.state_enabled};
        states[1] = new int[]{android.R.attr.state_focused, android.R.attr.state_enabled};
        states[2] = new int[]{android.R.attr.state_enabled};
        states[3] = new int[]{android.R.attr.state_focused};
        states[4] = new int[]{android.R.attr.state_window_focused};
        ColorStateList colorList = new ColorStateList(states, colors);
        return colorList;
    }


    public static boolean hasKitkat() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    }

    /**
     * 获取状态栏高度
     * @return
     */
    public static int getStatusBarHeight() {
        Resources resources = ContextProvider.getApplicationContext().getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen","android");
        int height = resources.getDimensionPixelSize(resourceId);
        LogInfo.log(TAG, "Status height:" + height);
        return height;
    }

    /**
     * 获取底部虚拟导航键高度
     * @return
     */
    public static int getNavigationBarHeight() {
        Resources resources = ContextProvider.getApplicationContext().getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        LogInfo.log(TAG, "Navi height:" + height);
        return height;
    }

    /**
     * 设置字体
     */
    public static void setViewTypeface(String typePath, TextView
            ...view){
        Typeface tf = Typeface.createFromAsset(ContextProvider.getApplicationContext().getAssets(),
                typePath);
        for(int i=0; i<view.length; i++) {
            view[i].setTypeface(tf);
        }
    }

    /**
     * 判断对象是否为空<br>
     * 1,字符串(null或者"")都返回true<br>
     * 2,数字类型(null或者0)都返回true<br>
     * 3,集合类型(null或者不包含元素都返回true)<br>
     * 4,数组类型不包含元素返回true(包含null元素返回false)<br>
     * 5,其他对象仅null返回true
     *
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null) { return true; }
        if (obj instanceof Number) {
            Number num = (Number) obj;
            if (num.intValue() == 0) {
                return true;
            } else {
                return false;
            }
        } else if (obj instanceof String) {
            String str = (String) obj;
            if ((str == null) || str.equals("")) {
                return true;
            } else {
                return false;
            }
        } else if (obj instanceof Collection<?>) {
            Collection<?> c = (Collection<?>) obj;
            return c.isEmpty();
        } else if (obj instanceof Map<?, ?>) {
            Map<?, ?> m = (Map<?, ?>) obj;
            return m.isEmpty();
        } else if (obj.getClass().isArray()) {
            int length = Array.getLength(obj);
            return length == 0 ? true : false;
        } else {
            return false;
        }
    }

    public static void setColorSchemeResources(SwipeRefreshLayout swipeRefreshLayout) {
        if (swipeRefreshLayout != null) {
            swipeRefreshLayout.setColorSchemeResources(R.color.color_5b5b5b);
        }
    }

    public static void setWindowStatusBarColor(Activity activity) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    window.setStatusBarColor(Color.TRANSPARENT);

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String formatNum(int num){
        if(num < 100){
            return num+"";
        }
        return "99+";
    }

    public static Integer[] createRandom(){
        Random random = new Random();
        Integer[] randomSet = new Integer[2];
        int randomNum1 = random.nextInt(10);
        randomSet[0] = randomNum1;
        int randomNum2 = random.nextInt(10);
        if(randomSet[0] != randomNum2){
            randomSet[1] = randomNum2;
        }else {
            if(randomNum2 == 1){
                randomSet[1] = 10 ;
            }else {
                randomSet[1] = randomNum2 -1;
            }
        }
        return randomSet;
    }
}

